<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Models\Domain;
use App\Models\DwzUrl;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException; // 引入 ValidationException
use Illuminate\Support\Str;

class DwzController extends Controller
{
    public function add(Request $request, $id)
    {
        $user = auth()->user();
        $domain = Domain::where('id', $id)->first();
        if (!$domain) {
            return response()->json(['status' => '0', 'msg' => '想干啥！飘了？']);
        }
        if ($domain['status'] != 1) {
            return response()->json(['status' => '0', 'msg' => '域名未审核通过,或已被封禁']);
        }
        if ($request->input('code') != null) {
            if ($user->id != $domain['uid']) {
                return response()->json(['status' => '0', 'msg' => '非域名所有者不能操作']);
            }
        }
        if ($domain['share'] != 1 or $user->id != $domain['uid']) {
            return response()->json(['status' => '0', 'msg' => '该域名不共享']);
        }
        try {
            // 验证 domain 和 url 字段不能为空，并确保 domain 唯一
            $validatedData = $request->validate([

                'url' => 'required',
            ], [

                'url.required' => '跳转链接不能为空',
            ]);
        } catch (ValidationException $e) {
            // 捕获验证异常并返回 JSON 格式的错误信息
            $errors = $e->errors();
            foreach ($errors as $field => $errorMessages) {
                $msg = reset($errorMessages);
                break; // 只取第一个错误信息
            }

            return response()->json(['status' => '0', 'msg' => $msg], 422);
        }

        // 获取表单数据
        $url = $request->input('url');
        $coses = $request->input('code');
        if (isset($coses)) {
            $code = $request->input('code');
        } else {
            $code = Str::random($domain['link_length']);
        }

        // 检查当前 domain_id 下是否存在相同 code 的记录
        $exists = DwzUrl::where('domain_id', $domain['id'])
            ->where('code', $code)
            ->exists();

        if ($exists) {
            return response()->json(['status' => '0', 'msg' => '该短网址后缀已存在'], 422);
        }

        // 保存表单数据，并显式添加 created_at 和 updated_at 字段
        DwzUrl::create([
            'uid' => $user->id, // 添加用户ID
            'url' => $url,
            'code' => $code,
            'domain_id' => $domain['id'],
            'status' => 1,
            'dwz' => "http://" . $domain['domain'] . '/' . $code,
            'ip' => $request->ip(),
            'created_at' => now(), // 添加创建时间
            'updated_at' => now(), // 添加更新时间
        ]);



        return response()->json(['status' => '1', 'msg' => '添加成功']);
    }
    public function edit(Request $request, $id)
    {
        $user = auth()->user();
        $dwzurl = DwzUrl::where('uid', $user->id)->where('id', $id)->first();
        if (!$dwzurl) {
            return response()->json(['status' => '0', 'msg' => '想干啥！飘了？']);
        }
        $domain = Domain::where('id', $dwzurl['domain_id'])->first();
        if ($domain['uid'] == $user->id) {
            $data = [
                'url' => $request->input('url'),
                'code' => $request->input('code'),
                'dwz' => "http://" . $domain['domain'] . '/' . $request->input('code'),
                'update_at' => time(),
            ];
        } else {
            $data = [
                'url' => $request->input('url'),
                'update_at' => time(),
            ];
        }

        $dwzurl->update($data);
        return response()->json(['status' => '1', 'msg' => '更新成功']);
    }
    public function del($id)
    {
        $dwzurl = DwzUrl::where('id', $id)->where('uid', auth()->user()->id)->first();
        if (!$dwzurl) {
            return response()->json(['status' => '0', 'msg' => '想干啥！飘了？']);
        }
        $dwzurl->delete();
        return response()->json(['status' => '1', 'msg' => '删除成功']);
    }
    public function dwz(Request $request, $id)
    {
        $domain  = Domain::where('id', $id)->first();
        if (!$domain) {
            return response()->json(['status' => '0', 'msg' => '域名不存在']);
        }
        if ($domain['status'] != 1) {
            return response()->json(['status' => '0', 'msg' => '域名已被禁用']);
        }
        if ($domain['share'] != 1) {
            return response()->json(['status' => '0', 'msg' => '该域名不共享']);
        }
        $api_token = $request->input('api_token');
        if (isset($api_token)) {
            $user= User::where('api_token', $request->input('api_token'))->first();
            if (!$user) {
                return response()->json(['status' => '0', 'msg' => 'api_key错误']);
            }else{
                $uid=  $user->id;
            }
        }else{
            $uid=$domain['uid'];
        }
        $code=Str::random($domain['link_length']);
        DwzUrl::create([
            'uid' => $uid, // 添加用户ID
            'url' => $request->input('url'),
            'code' => $code,
            'domain_id' => $domain['id'],
            'status' => 1,
            'dwz' => "http://" . $domain['domain'] . '/' . $code,
            'ip' => $request->ip(),
            'created_at' => now(), // 添加创建时间
            'updated_at' => now(), // 添加更新时间
        ]);



        return response()->json(['status' => '1', 'msg' => '生成成功','dwz'=>"http://" . $domain['domain'] . '/' . $code]);
        
        
    }
}
